package com.inspur.demo.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 自定义参数检查过滤器
 *
 * @author li.peng02
 * @version 1.0
 * @date 2021-06-30 17:12
 */
@Component
public class CheckParamGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            String name = config.getName();
            String value = config.getValue();

            String sendNameStr = exchange.getRequest().getQueryParams().getFirst(name);
            if (StringUtils.isEmpty(sendNameStr)) {
                exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
                exchange.getResponse().getHeaders().set("errorMsg", name + " parameter can not be empty");
                return exchange.getResponse().setComplete();
            }

            if (!sendNameStr.equals(value)) {
                exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
                exchange.getResponse().getHeaders().set("errorMessage", name + " parameter value need equal " + value);
                return exchange.getResponse().setComplete();
            }

            // 继续传递
            return chain.filter(exchange);
        };
    }
}
